using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.InsightWebControls;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;

namespace PHSRAG.Insight21.Agreements
{
    public partial class AgreementsProjectDetails : NoCachePage
    {
        #region Constants

        private const string AddAnnotation = "Add Note";
        private const string SaveAnnotation = "Save Note";

        #endregion

        #region Instance Variables (Private)

        private ICachePolicy cachePolicy;
        private Agreement currentAgreement;

        #endregion

        #region Event Handlers

        protected void OnAddNewAnnotation(object sender, EventArgs e)
        {
            if (addAnnotation.Text == AddAnnotation)
            {
                UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
                Debug.Assert(userContext != null);
                newAnnotation.UserName = userContext.Username;
                newAnnotation.Date = DateTime.Now.ToString();
                newAnnotation.Visible = true;
                addAnnotation.Text = SaveAnnotation;
            }
            else
            {
                try
                {
                    if (currentAgreement == null)
                    {
                        currentAgreement = cachePolicy.GetCachedObject("currentAgreement") as Agreement;
                    }

                    DataTable annotations = currentAgreement.ProjectDetails.Annotations.GetDataContainer().Tables["Annotations"];

                    DataRow newRow = annotations.NewRow();

                    //Retrieve UserContext object to retreive ApplicationUserId, and CreateDate
                    UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
                    if (userContext == null)
                    {
                        throw new Exception("The user context information for the logged in user was not found in the cache.");
                    }

                    // add in the data.
                    newRow["AnnotationContainerId"] = currentAgreement.ProjectDetails.AnnotationContainerId;
                    newRow["AnnotationTypeId"] = 1;
                    newRow["Title"] = newAnnotation.Title;
                    newRow["Detail"] = newAnnotation.Description;
                    newRow["SbsOriginatorTypeId"] = 1;
                    newRow["FwkApplicationUserId"] = userContext.ApplicationUserId;
                    newRow["UserName"] = newAnnotation.UserName;
                    newRow["CreateDate"] = newAnnotation.Date;

                    annotations.Rows.Add(newRow);

                    // now save the agreeement
                    currentAgreement.Save(DataAccess.GetConnectionString());
                    annotationDataGrid.DataSource = annotations;
                    annotationDataGrid.DataBind();
                }
                catch (Exception ex)
                {
                    annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
                    ExceptionReport.WriteToEventLog("AgreementsProjectDetails", ex, true, ExceptionReport.ReportType.Error);
                }
                finally
                {
                    newAnnotation.Title = string.Empty;
                    newAnnotation.Description = string.Empty;
                    newAnnotation.Visible = false;
                    addAnnotation.Text = AddAnnotation;
                }
            }
        }

        /// <summary>
        /// Purges the cache and sets the correct search context level before the breadcrumb performs a redirect.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnNavigate(object sender, CommandEventArgs e)
        {
            if (((CommandEventArgs) (e.CommandArgument)).CommandName == Convert.ToString((int) SearchCriteria.Level.Summary))
            {
                //set the search context's level to the correct level
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                searchContext.CurrentLevel = SearchCriteria.Level.Summary;
            }
            PurgeCache();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            breadCrumb.Add("Project Details",
                "AgreementsProjectDetails.aspx",
                Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

            if (!IsPostBack)
            {
                Agreement agreement;

                try
                {
                    Hashtable h = (Hashtable) cachePolicy.GetCachedObject(Constants.AgreementsConstants.AgreementDetailsKey);
                    int agreementID = Convert.ToInt32(h[Keys.AgreementIdKey]);
                    string passedFundNumber = Convert.ToString(h[Keys.FundNumberKey]);
                    agreement = new Agreement(cachePolicy);
                    agreement.Load(DataAccess.GetConnectionString(), agreementID, passedFundNumber);

                    Debug.Assert(agreement != null);

                    addAnnotation.Text = AddAnnotation;
                    newAnnotation.Visible = false;

                    cachePolicy.Cache("currentAgreement", currentAgreement = agreement);

                    int budgetYear = (h[Keys.BudgetYearKey] == null) ? 0 : (int) h[Keys.BudgetYearKey];
                    projectHeaderBar.LoadProjectHeader(passedFundNumber, agreement.ResourceID, budgetYear);
                    //Fetch ChiefCode TrackIT# 7978
                    string strchiefCode = String.Empty;
                    if (projectHeaderBar.ChiefCode != null)
                    {
                        strchiefCode = projectHeaderBar.ChiefCode;
                    }

                    //Get key contact info 
                    if (!string.IsNullOrEmpty(projectHeaderBar.ChiefCode) && !string.IsNullOrEmpty(projectHeaderBar.Institution))
                    {
                        DisplayKeyContacts(projectHeaderBar.Institution, projectHeaderBar.ChiefCode, projectHeaderBar.SponsorTypeId);
                    }


                    h[Keys.RefreshBudgetDetailDataKey] = true;
                    cachePolicy.Cache(Constants.AgreementsConstants.AgreementDetailsKey, h);

                    agreementStatus.Text = agreement.StatusType;
                    budgetStartEnd.Text = agreement.BudgetStartEndDate;
                    projectStartEnd.Text = agreement.ProjectStartEndDate;

                    // check the IC Rates exist.
                    icBasis.Text = agreement.ICBasis;
                    if (agreement.ProjectDetails.ICRate1 != decimal.MinValue)
                    {
                        icRate1.Text = agreement.ProjectDetails.ICRate1.ToString();
                    }

                    if (agreement.ProjectDetails.ICRate2 != decimal.MinValue)
                    {
                        icRate2.Text = agreement.ProjectDetails.ICRate2.ToString();
                    }

                    //Append Chief Code to Dept/Unit Trackit# 7978
                    deptUnit.Text = agreement.ProjectDetails.OrganizationName + " - " + strchiefCode;
                    institution.Text = agreement.ProjectDetails.FacilityName;

                    lbRexFolderNumber.InnerText = agreement.ProjectDetails.RexFolderNumber;
                    if (Settings.GetKeyValue(UIUtility.IsInfoEdReadyForSSO, false))
                    {
                        string strInfoEdLandingPageURL = Settings.GetKeyValue(UIUtility.InfoEdTargetPageForAgreementsProjectDetails,"");
                        strInfoEdLandingPageURL = string.Format(strInfoEdLandingPageURL, Settings.GetKeyValue(UIUtility.InfoEdLandingPageURLKey, ""),agreement.ProjectDetails.RexFolderNumber);
                        lbRexFolderNumber.HRef = strInfoEdLandingPageURL;
                    }
                    

                    sponsorName.Text = agreement.ProjectDetails.Sponsor.ShortName;
                    sponsorNumber.Text = agreement.ProjectDetails.SponsorNumber;
                    sponsorTypeName.Text = agreement.SponsorTypeName;

                    agreementType.Text = agreement.AgreementType;
                    activityType.Text = agreement.ActivityType;

                    string fundNumberValue = agreement.FundNumber;
                    if (fundNumberValue != string.Empty)
                    {
                        agreement.ProjectDetails.RequestedFundNumber = fundNumber.Text = fundNumberValue;
                        fundType.Text = agreement.ProjectDetails.Fund.FundType;
                        fundCode.Text = agreement.FundCode;
                        bicsLegacyNo.Text = agreement.ProjectDetails.Fund.CostCenterNumber;
                        accountCycle.Text = agreement.ProjectDetails.Fund.AccountCycleType;
                        activation.Text = agreement.ProjectDetails.Fund.ActivationDate;
                        inactivation.Text = agreement.ProjectDetails.Fund.InactivationDate;
                        FNumberAndMRN.Text = agreement.ProjectDetails.Fund.FNumberAndMRN;
                        documentId.Text = agreement.ProjectDetails.Fund.DocumentId;
                    }

                    if (agreement.ProjectDetails.Annotations.GetDataContainer().Tables["Annotations"].Rows.Count > 0)
                    {
                        annotationDataGrid.DataSource = agreement.ProjectDetails.Annotations.GetDataContainer().Tables["Annotations"];
                        annotationDataGrid.DataBind();
                    }
                    agreementDetailsSubNavigation.SelectedLink = AgreementDetailsSubNavigation.ProjectDetailCommand;
                }
                catch (Exception ex)
                {
                    annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
                    ExceptionReport.WriteToEventLog("AgreementsProjectDetails", ex, true, ExceptionReport.ReportType.Error);
                }
            }
            else
            {
                object o = cachePolicy.GetCachedObject("currentAgreement");
                if (o == null)
                {
                    currentAgreement = (Agreement) o;
                }
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link(s) and purges the cache before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
            agreementsSubNavigation.Reset();
            agreementDetailsSubNavigation.Reset();
        }

        /// <summary>
        /// Purges the cache before the agreements subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        /// <summary>
        /// Purges the cache before the agreement details subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnDetailsSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Uncaches all objects with data for this page.
        /// </summary>
        private void PurgeCache()
        {
            System.Diagnostics.Trace.WriteLine("Purging ProjectDetails...");
            cachePolicy.UnCache("currentAgreement");
        }

        private void DisplayKeyContacts(string strInstitution, string strChiefCode, string strSponsorTypeId)
        {
            try
            {
                DataTable dt = Agreement.GetKeyContacts(DataAccess.GetConnectionString(), strInstitution, strChiefCode, strSponsorTypeId);

                foreach (DataRow dr in dt.Rows)
                {
                    switch (dr["RoleId"].ToString())
                    {
                        case "1":

                            ltDeppAdmin.Visible = true;
                            ltDeptAdminNumber.Visible = true;
                            deptAdministrator.Visible = true;
                            deptAdminNumber.Visible = true;
                            deptAdminEmail.Visible = true;
                            anDeptAdminEmail.Visible = true;
                            anDeptAdminEmail.HRef = string.Format("mailto:{0}", dr["Email"]);
                            anDeptAdminEmail.InnerText = dr["Email"].ToString();

                            deptAdministrator.Text = dr["FullName"].ToString();
                            deptAdminNumber.Text = dr["phone"].ToString();
                            break;
                        case "2":
                            ltPreAwdAdmin.Visible = true;
                            ltPreAwdAdmNumber.Visible = true;
                            preAwardAdminName.Visible = true;
                            preAwardAdminNumber.Visible = true;
                            preAwdAdmEmail.Visible = true;
                            anPreAwdAdminEmail.Visible = true;
                            anPreAwdAdminEmail.HRef = string.Format("mailto:{0}", dr["Email"]);
                            anPreAwdAdminEmail.InnerText = dr["Email"].ToString();


                            preAwardAdminName.Text = dr["FullName"].ToString();
                            preAwardAdminNumber.Text = dr["phone"].ToString();
                            break;
                        case "3":
                            ltPostAwdAdmin.Visible = true;
                            ltPostAwdAdmNumber.Visible = true;
                            postAwardAdminName.Visible = true;
                            postAwardAdminNumber.Visible = true;
                            postAwdAdmEmail.Visible = true;
                            anPostAdmAdmEmail.Visible = true;

                            anPostAdmAdmEmail.HRef = string.Format("mailto:{0}", dr["Email"]);
                            anPostAdmAdmEmail.InnerText = dr["Email"].ToString();

                            postAwardAdminName.Text = dr["FullName"].ToString();
                            postAwardAdminNumber.Text = dr["phone"].ToString();
                            break;
                        case "4":
                            ltSubContAdmin.Visible = true;
                            ltSubContAdmNumber.Visible = true;
                            subContractAdmin.Visible = true;
                            subContractAdminNumber.Visible = true;
                            subConAdmEmail.Visible = true;
                            anSubContEmail.Visible = true;
                            anSubContEmail.HRef = string.Format("mailto:{0}", dr["Email"]);
                            anSubContEmail.InnerText = dr["Email"].ToString();

                            subContractAdmin.Text = dr["FullName"].ToString();
                            subContractAdminNumber.Text = dr["phone"].ToString();
                            break;
                        case "5":
                            ltIRBAdmin.Visible = true;
                            ltIRBAdminNumber.Visible = true;
                            IRBAdmin.Visible = true;
                            IRBAdminNumber.Visible = true;
                            IRBAdmEmail.Visible = true;
                            anIRBAdmEmail.Visible = true;
                            anIRBAdmEmail.HRef = string.Format("mailto:{0}", dr["Email"]);
                            anIRBAdmEmail.InnerText = dr["Email"].ToString();

                            IRBAdmin.Text = dr["FullName"].ToString();
                            IRBAdminNumber.Text = dr["phone"].ToString();
                            break;

                        case "6":
                            contactPersonText.Visible = true;
                            contactPerson.Visible = true;
                            contactPhoneText.Visible = true;
                            contactPhone.Visible = true;
                            contactEmailText.Visible = true;
                            contactEmail.Visible = true;
                            contactEmail.HRef = string.Format("mailto:{0}", dr["Email"]);
                            contactEmail.InnerText = dr["Email"].ToString();

                            contactPerson.Text = dr["FullName"].ToString();
                            contactPhone.Text = dr["phone"].ToString();
                            break;
                        default:
                            break;
                    }
                }
            }
            catch
            {
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion
    }
}